package org.jsola.hr.provider.impl;

import groovy.lang.Lazy;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.jsola.admin.service.ISiteService;
import org.jsola.admin.vo.SiteVO;
import org.jsola.common.StrKit;
import org.jsola.core.entity.BaseDO;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.HrLogKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.entity.*;
import org.jsola.hr.provider.IPermissionProviderService;
import org.jsola.hr.provider.IUserProviderService;
import org.jsola.hr.query.permission.RoleMemberQuery;
import org.jsola.hr.service.*;
import org.jsola.hr.vo.ChildCompanyListVO;
import org.jsola.hr.vo.CompanyVO;
import org.jsola.hr.vo.HrUserVO;
import org.jsola.hr.vo.permission.RoleMemberVO;
import org.jsola.permission.constant.PermissionConstants;
import org.jsola.permission.constant.RoleMemberTypeEnum;
import org.jsola.permission.constant.RoleTypeEnum;
import org.jsola.permission.dao.IRoleDAO;
import org.jsola.permission.dao.IRoleMemberDAO;
import org.jsola.permission.dto.*;
import org.jsola.permission.entity.*;
import org.jsola.permission.query.GroupQuery;
import org.jsola.permission.query.GroupUserQuery;
import org.jsola.permission.query.RoleQuery;
import org.jsola.permission.service.*;
import org.jsola.permission.vo.*;
import org.jsola.user.core.TokenUser;
import org.jsola.user.dao.IUserDAO;
import org.jsola.user.entity.UserDO;
import org.jsola.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

import static org.jsola.hr.constant.HrPermissionConstants.*;
import static org.jsola.permission.constant.PermissionConstants.DEFAULT_SITE_ID;

/**
 * @author june
 */
@Service("hrPermissionProviderService")
@Slf4j
public class PermissionProviderServiceImpl implements IPermissionProviderService {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IRoleMemberService roleMemberService;

    @Autowired
    private IRoleMemberDAO roleMemberDAO;

    @Autowired
    private IRoleDAO roleDAO;

    @Autowired
    private IAuthService authService;

    @Autowired
    private IRightService rightService;

    @Autowired
    private IUserProviderService userProviderService;

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IChildCompanyService childCompanyService;

    @Autowired
    private IGroupCompanyService groupCompanyService;

    @Autowired
    private ISiteService siteService;

    @Autowired
    private IUserRoleCompanyService userRoleCompanyService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private IEmpInfoService empInfoService;

    @Autowired
    private IGroupService groupService;

    @Autowired
    private IGroupUserService groupUserService;


    @Override
    public boolean hasRight(String userId, String siteId, String subjectId, String subjectType) {
        return authService.hasRight(userId, siteId, subjectId, subjectType);
    }

    @Override
    public boolean hasRight(String userId, String siteId, String permissionString) {
        return authService.hasRight(userId, siteId, permissionString);
    }

    @Override
    public boolean hasAllRight(String userId, String siteId, String... permissionString) {
        return authService.hasAllRight(userId, siteId, permissionString);
    }

    @Override
    public boolean hasAnyRight(String userId, String siteId, String... permissionString) {
        return authService.hasAnyRight(userId, siteId, permissionString);
    }

    @Override
    public boolean hasObjRight(String userId, String siteId, String subjectId, String permissionString) {
        return authService.hasObjRight(userId, siteId, subjectId, permissionString);
    }

    @Override
    public boolean hasObjAllRight(String userId, String siteId, String subjectId, String... permissionString) {
        return authService.hasObjAllRight(userId, siteId, subjectId, permissionString);
    }

    @Override
    public boolean hasObjAnyRight(String userId, String siteId, String subjectId, String... permissionString) {
        return authService.hasObjAnyRight(userId, siteId, subjectId, permissionString);
    }

    @Override
    public boolean isAdmin(String userId, String siteId, String subjectId, String subjectType) {
        return roleService.hasAdminRole(userId, subjectType, subjectId, siteId);
    }

    @Override
    public boolean isAdminValidaGroup(String userId, String siteId, String subjectId, String subjectType) {
        return roleService.hasAdminRoleValidGroup(userId, subjectType, subjectId, siteId);
    }

    @Override
    public List<RoleDO> querySiteRoleList(String subjectType, String siteId) {
        return roleService.findRoleListBySubjectType(subjectType, siteId);
    }

    @Override
    public void addRoleMember(String userId, Long roleId, String subjectType, String subjectId, TokenUser tokenUser) {
        RoleMemberAddDTO roleMemberAddDTO = new RoleMemberAddDTO();
        roleMemberAddDTO.setMemberId(userId);
        roleMemberAddDTO.setRoleId(roleId);
        roleMemberAddDTO.setSubjectType(subjectType);
        roleMemberAddDTO.setSubjectId(subjectId);
        roleMemberAddDTO.setType(RoleMemberTypeEnum.USER.getValue());
        roleMemberService.save(roleMemberAddDTO, tokenUser);
    }

    @Override
    public void addGroupRoleMember(String groupId, Long roleId, String subjectType, String subjectId, TokenUser tokenUser) {
        RoleMemberAddDTO roleMemberAddDTO = new RoleMemberAddDTO();
        roleMemberAddDTO.setMemberId(groupId);
        roleMemberAddDTO.setRoleId(roleId);
        roleMemberAddDTO.setSubjectType(subjectType);
        roleMemberAddDTO.setSubjectId(subjectId);
        roleMemberAddDTO.setType(RoleMemberTypeEnum.GROUP.getValue());
        roleMemberService.save(roleMemberAddDTO, tokenUser);
    }

    @Override
    public List<Long> findRoleIdListByUserId(String userId, String subjectType, String subjectId, String siteId) {
        return roleMemberService.findRoleIdListByUserId(userId, subjectType, subjectId, siteId);
    }

    @Override
    public void deleteRoleMember(String userId, Long roleId, String subjectType, String subjectId, String siteId) {
        roleMemberService.deleteRoleMembers(Collections.singletonList(userId), roleId, siteId, subjectType, subjectId);
    }

    @Override
    public void deleteRoleMemberById(Long roleMemberId, TokenUser tokenUser) {
        RoleMemberDO roleMemberDO = roleMemberService.selectDOById(roleMemberId, tokenUser.getSiteId());
        if (roleMemberDO != null) {
            roleMemberService.deleteByIds(tokenUser, roleMemberId);
        }
    }

    @Override
    public RoleDO findRoleById(Long roleId, String siteId) {
        return roleService.selectDOById(roleId, siteId);
    }

    @Override
    public List<RoleDO> selectRoleByIds(List<Long> roleIds, String siteId) {
        return roleService.selectDOByIds(roleIds, siteId);
    }

    @Override
    public RoleVO addRole(RoleAddDTO roleAddDTO, TokenUser tokenUser) {
        return roleService.save(roleAddDTO, tokenUser);
    }

    @Override
    public void updateRole(RoleUpdateDTO roleUpdateDTO, TokenUser tokenUser) {
        roleService.update(roleUpdateDTO, tokenUser);
    }

    @Override
    public void deleteRoleById(Long roleId, TokenUser tokenUser) {
        roleService.deleteByIds(tokenUser, roleId);
    }

    @Override
    public void deleteRoleByIds(TokenUser tokenUser, Long... roleIds) {
        List<RoleDO> roleDOList = selectRoleByIds(Arrays.asList(roleIds), tokenUser.getSiteId());
        roleService.deleteByIds(tokenUser, roleDOList.parallelStream().map(BaseDO::getId).toArray(Long[]::new));
    }

    @Override
    public List<RoleListVO> queryRoleList(RoleQuery roleQuery, String siteId) {
        return roleService.select(roleQuery, siteId);
    }

    @Override
    public List<RoleDO> findRoleListByUserId(String userId, String subjectType, String subjectId, String siteId) {
        return roleService.findRoleListByUserId(userId, subjectType, subjectId, siteId);
    }

    @Override
    public List<RoleRightListVO> queryRightList(String subjectType, String siteId, Long roleId) {
        return rightService.queryRightList(subjectType, siteId, roleId);
    }

    @Override
    public void saveRoleRight(String currUserId, Long roleId, String subjectType, String[] subjectIdArray, Long[] permissionIdArray, String siteId) {
        rightService.saveRoleRight(currUserId, roleId, subjectType, subjectIdArray, permissionIdArray, siteId);
    }

    @Override
    public String findMemberIdBySubject(String type, String subjectType, String subjectId, String siteId) {
        org.jsola.permission.query.RoleMemberQuery roleMemberQuery = new org.jsola.permission.query.RoleMemberQuery();
        roleMemberQuery.setType(type);
        roleMemberQuery.setSubjectType(subjectType);
        roleMemberQuery.setSubjectId(subjectId);
        List<RoleMemberListVO> roleMemberListVOList = roleMemberService.select(roleMemberQuery, siteId);
        //user删掉的过滤
        List<String> userIds = roleMemberListVOList.stream().map(RoleMemberListVO::getMemberId).collect(Collectors.toList());
        userIds = userProviderService.selectUserByIds(userIds).stream().map(UserDO::getId).collect(Collectors.toList());
        List<String> finalUserIds = userIds;
        roleMemberListVOList = roleMemberListVOList.stream().filter(p -> {
            return finalUserIds.contains(p.getMemberId());
        }).collect(Collectors.toList());
        RoleMemberListVO roleMemberListVO = roleMemberListVOList.stream().min(new Comparator<RoleMemberListVO>() {
            @Override
            public int compare(RoleMemberListVO o1, RoleMemberListVO o2) {
                return o1.getGmtCreate().after(o2.getGmtCreate()) ? 1 : 0;
            }
        }).get();
        return roleMemberListVO.getMemberId();
    }

    @Override
    public List<String> findMemberListBySubject(String type, String subjectType, String subjectId, String siteId) {
        org.jsola.permission.query.RoleMemberQuery roleMemberQuery = new org.jsola.permission.query.RoleMemberQuery();
        roleMemberQuery.setType(type);
        roleMemberQuery.setSubjectType(subjectType);
        roleMemberQuery.setSubjectId(subjectId);
        List<RoleMemberListVO> roleMemberListVOList = roleMemberService.select(roleMemberQuery, siteId);
        //user删掉的过滤
        List<String> userIds = roleMemberListVOList.stream().map(RoleMemberListVO::getMemberId).collect(Collectors.toList());
        userIds = userProviderService.selectUserByIds(userIds).stream().map(UserDO::getId).collect(Collectors.toList());
        return userIds;
    }

    @Override
    public List<RoleMemberVO> queryRoleMemberList(RoleMemberQuery roleMemberQuery, TokenUser tokenUser) {
        List<String> roleMemberList = roleMemberService.findMemberIdBySubject(PermissionConstants.ROLE_MEMBER_TYPE_USER,
                COMPANY_SUBJECT_TYPE, roleMemberQuery.getCompanyId(), tokenUser.getSiteId());
        List<RoleMemberVO> resultList = new ArrayList<>();
        for (String memberId : roleMemberList) {
            RoleMemberVO roleMemberVO = new RoleMemberVO();
            List<RoleDO> userRoleList = this.findRoleListByUserId(memberId, COMPANY_SUBJECT_TYPE, roleMemberQuery.getCompanyId(), tokenUser.getSiteId());
            if (!CollectionUtils.isEmpty(userRoleList)) {
                roleMemberVO.setRoleName(userRoleList.get(0).getName());
                roleMemberVO.setRoleId(userRoleList.get(0).getId());
            }
            roleMemberVO.setUserId(memberId);
            //查询用户的手机号和用户名
            UserDO userDO = userProviderService.selectUserById(memberId);
            roleMemberVO.setUserName(userDO == null ? "" : userDO.getName());
            roleMemberVO.setPhone(userDO == null ? "" : userDO.getPhone());
            //过滤条件
            if (StrKit.isNotEmpty(roleMemberQuery.getUserName()) && !roleMemberVO.getUserName().contains(roleMemberQuery.getUserName())) {
                continue;
            }
            if (StrKit.isNotEmpty(roleMemberQuery.getPhone()) && !roleMemberVO.getPhone().contains(roleMemberQuery.getPhone())) {
                continue;
            }
            resultList.add(roleMemberVO);
        }

        return resultList;
    }

    @Override
    public List<RoleMemberVO> queryRoleMemberListFilterNameAndPhone(RoleMemberQuery roleMemberQuery, TokenUser tokenUser) {
        // 有分组权限的用户
        List<UserRoleCompanyDO> userRoleCompanyDOList = userRoleCompanyService
                .selectByChildCompany(roleMemberQuery.getCompanyId(), tokenUser.getSiteId());
        // 去重
        List<String> userIds = userRoleCompanyDOList.parallelStream().map(UserRoleCompanyDO::getUserId)
                .distinct().collect(Collectors.toList());
        List<RoleMemberVO> resultList = new ArrayList<>();
        for (String userId : userIds) {
            RoleMemberVO roleMemberVO = new RoleMemberVO();
            List<RoleDO> userRoleList = this.findRoleListByUserId(userId
                    , COMPANY_SUBJECT_TYPE, roleMemberQuery.getCompanyId(), tokenUser.getSiteId());
            if (!CollectionUtils.isEmpty(userRoleList)) {
                roleMemberVO.setRoleName(userRoleList.get(0).getName());
                roleMemberVO.setRoleId(userRoleList.get(0).getId());
            }
            roleMemberVO.setUserId(userId);
            //查询用户的手机号和用户名
            UserDO userDO = userProviderService.selectUserById(userId);
            roleMemberVO.setUserName(userDO == null ? "" : userDO.getName());
            roleMemberVO.setPhone(userDO == null ? "" : userDO.getPhone());
            //过滤条件
            if (StrKit.isNotEmpty(roleMemberQuery.getUserName())) {
                if ((StrKit.isNotEmpty(roleMemberQuery.getUserName()) && roleMemberVO.getUserName().contains(roleMemberQuery.getUserName())) ||
                        (StrKit.isNotEmpty(roleMemberQuery.getPhone()) && roleMemberVO.getPhone().contains(roleMemberQuery.getPhone()))) {
                    resultList.add(roleMemberVO);
                }
            } else {
                resultList.add(roleMemberVO);
            }
        }

        return resultList;
    }

    @Override
    public void addRoleMemberBatch(List<RoleMemberAddDTO> roleMemberAddDTOList, TokenUser tokenUser) {
        roleMemberService.batchSave(roleMemberAddDTOList, tokenUser);
    }

    @Override
    public Map<String, Long> getRoleRightCountMap(String subjectType, String siteId) {
        return rightService.getRoleRightCountMap(subjectType, siteId);
    }

    @Override
    public Map<String, Long> getRoleRightCountMap(List<String> subjectTypeList, String siteId) {
        return rightService.getRoleRightCountMap(subjectTypeList, siteId);
    }

    @Override
    public List<RoleMemberListVO> selectRoleMemberList(org.jsola.permission.query.RoleMemberQuery roleMemberQuery, String siteId) {
        return roleMemberService.select(roleMemberQuery, siteId);
    }

    @Override
    public List<String> listCompanyUserHasRole(String userId, String siteId) {
        // 获取用户有权限的分公司
        List<String> childCompanyIdList = roleMemberService.findUserHasRightSubjectId(userId, COMPANY_SUBJECT_TYPE, siteId);
        if (CollectionUtils.isEmpty(childCompanyIdList)) {
            return null;
        }
        List<String> companyIdList = new ArrayList<>();

        childCompanyIdList.parallelStream().forEach(
                childCompanyId -> {
                    ChildCompanyDO childCompany = childCompanyService.selectDOById(childCompanyId, siteId);

                    if (Objects.isNull(childCompany)) {
                        // 不是分公司
                        companyIdList.add(childCompanyId);
                    } else {
                        // 是分公司,获取分公司的分管单位
                        List<GroupCompanyDO> groupCompanyList = groupCompanyService.listByGroupId(childCompanyId, siteId);
                        if (!CollectionUtils.isEmpty(groupCompanyList)) {
                            // 是不是全部用工单位
                            GroupCompanyDO groupCompany = groupCompanyList.parallelStream()
                                    .filter(GroupCompanyDO::getIsAll)
                                    .findFirst().orElse(null);

                            List<String> companyGroupIdList;
                            if (Objects.nonNull(groupCompany)) {
                                // 全部用工单位
                                List<CompanyVO> companyList = companyService.listVoByIds(siteId, null);

                                companyGroupIdList = companyList.parallelStream()
                                        .map(CompanyVO::getId)
                                        .collect(Collectors.toList());
                            } else {
                                // 非全部用工单位
                                companyGroupIdList = groupCompanyList.parallelStream()
                                        .map(GroupCompanyDO::getCompanyId)
                                        .collect(Collectors.toList());
                            }

                            // 获取账号有权限的分公司
                            List<UserRoleCompanyDO> userRoleCompanyList = userRoleCompanyService.listByUserAndChildCompany(userId, childCompanyId, siteId);
                            if (!(CollectionUtils.isEmpty(userRoleCompanyList) || userRoleCompanyList.get(0).getIsAllEmployer())) {
                                // 用户有权限的用工单位
                                List<String> employerIdList = userRoleCompanyList.parallelStream()
                                        .map(UserRoleCompanyDO::getEmployerId).collect(Collectors.toList());
                                // 取交集
                                companyGroupIdList.retainAll(employerIdList);
                            }
                            companyIdList.addAll(companyGroupIdList);
                        }
                    }
                }
        );
        return companyIdList;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void deleteUserRoleMember(TokenUser tokenUser, String... userId) {
        Arrays.stream(userId).forEach(id -> {
            //查询用户hr角色
            List<Long> roleIdList = this.findRoleIdListByUserId(id, HR_SUBJECT_TYPE, null, tokenUser.getSiteId());
            roleIdList.forEach(roleId ->
                    this.deleteRoleMember(id, roleId, HR_SUBJECT_TYPE, HR_DEFAULT_SUBJECT_ID, tokenUser.getSiteId())
            );
            //查询用户company角色
            roleIdList = this.findRoleIdListByUserId(id, COMPANY_SUBJECT_TYPE, null, tokenUser.getSiteId());
            roleIdList.forEach(roleId ->
                    this.deleteRoleMember(id, roleId, COMPANY_SUBJECT_TYPE, null, tokenUser.getSiteId())
            );
        });
    }

    @Override
    public void addUserToCompanyAdmin(String companyId, TokenUser tokenUser, String... userIds) {
        if (userIds == null || userIds.length == 0) {
            throw new ParamException("请传递要添加的人员");
        }
        // 获取公司管理员角色
        RoleDO roleAdmin = getRoleCompanyAdmin(tokenUser.getSiteId());
        //添加为公司管理员
        for (String userId : userIds) {
            addRoleMember(userId, roleAdmin.getId(), COMPANY_SUBJECT_TYPE, companyId, tokenUser);
        }
        HrLogKit.logForSave("将userIds:" + userIds + " 加为公司companyId:" + companyId + " 的公司管理员", "addUserToCompanyAdmin", companyId, tokenUser);
    }

    /**
     * 获取公司管理员角色
     *
     * @param siteId 站点
     * @return 公司管理员角色
     */
    private RoleDO getRoleCompanyAdmin(String siteId) {
        List<RoleDO> roleList = querySiteRoleList(COMPANY_SUBJECT_TYPE, siteId);

        ParamException.notEmpty(roleList, "公司下暂无管理员角色,请联系管理员");
        //第一条一定是公司管理员
        RoleDO roleDO = roleList.stream()
                .filter(role -> RoleTypeEnum.ADMIN.getValue().equals(role.getType()))
                .findFirst()
                .orElse(null);
        ParamException.notNull(roleDO, "公司下暂无管理员角色,请联系管理员");

        return roleDO;
    }

    @Override
    public void addGroupToCompanyAdmin(String companyId, TokenUser tokenUser, String... groupIds) {
        if (groupIds == null || groupIds.length == 0) {
            throw new ParamException("请传递要添加的组");
        }
        // 获取公司管理员角色
        RoleDO roleAdmin = getRoleCompanyAdmin(tokenUser.getSiteId());
        //添加为公司管理员
        for (String groupId : groupIds) {
            addGroupRoleMember(groupId, roleAdmin.getId(), COMPANY_SUBJECT_TYPE, companyId, tokenUser);
        }
        HrLogKit.logForSave("groupIds:" + groupIds + " 加为公司companyId:" + companyId + " 的公司管理员", "addGroupToCompanyAdmin", companyId, tokenUser);
    }

    @Override
    public void removeUserFormCompanyAdmin(String companyId, TokenUser tokenUser, String... userIds) {
        if (userIds == null || userIds.length == 0) {
            throw new ParamException("请传递要移除的人员");
        }
        // 获取公司管理员角色
        RoleDO roleAdmin = getRoleCompanyAdmin(tokenUser.getSiteId());
        // 从公司管理员移除
        for (String userId : userIds) {
            deleteRoleMember(userId, roleAdmin.getId(), COMPANY_SUBJECT_TYPE, companyId, tokenUser.getSiteId());
        }
        HrLogKit.logForSave("将userIds:" + userIds + " 从公司companyId:" + companyId + " 的公司管理员移除", "addUserToCompanyAdmin", companyId, tokenUser);
    }

    @Override
    public void removeGroupFormCompanyAdmin(String companyId, TokenUser tokenUser, String... groupIds) {
        if (groupIds == null || groupIds.length == 0) {
            throw new ParamException("请传递要移除的组");
        }
        // 获取公司管理员角色
        RoleDO roleAdmin = getRoleCompanyAdmin(tokenUser.getSiteId());
        //从公司管理员移除
        for (String groupId : groupIds) {
            deleteRoleMember(groupId, roleAdmin.getId(), COMPANY_SUBJECT_TYPE, companyId, tokenUser.getSiteId());
        }
        HrLogKit.logForSave("groupIds:" + groupIds + " 从公司companyId:" + companyId + " 的公司管理员移除", "addGroupToCompanyAdmin", companyId, tokenUser);
    }

    @Override
    public List<PermissionDO> getPermissionList(String subjectType) {
        PermissionDO queryPermission = new PermissionDO();
        queryPermission.setSubjectType(subjectType);
        return permissionService.findPermissionList(queryPermission, "0");
    }

    @Override
    public List<PermissionDO> getPermissionListByEnName(List<String> enNameList) {
        return permissionService.findPermissionList(enNameList, DEFAULT_SITE_ID);
    }

    @Override
    public List<String> getPermissionStringList(List<PermissionDO> permissionList) {
        return permissionService.getPmsStringsByPermission("0", permissionList);
    }

    @Override
    public String getSiteName(String siteId) {
        SiteVO siteVO = siteService.selectById(siteId, null);
        // 主公司
        return Objects.nonNull(siteVO) ? siteVO.getName() : "";
    }

    @Override
    public Integer userIsSuperme(TokenUser tokenUser) {
        List<String> childCompanyIdList = roleMemberService.findUserHasRightSubjectId(tokenUser.getUserId(), COMPANY_SUBJECT_TYPE, tokenUser.getSiteId());
        if (CollectionUtils.isEmpty(childCompanyIdList)) {
            return 3;
        }
        // 总公司成员
        if (childCompanyIdList.contains("supreme")) {
            return 1;
        } else {
            List<ChildCompanyListVO> childCompanyList = childCompanyService.listByIdList(childCompanyIdList, tokenUser.getSiteId());
            if (!CollectionUtils.isEmpty(childCompanyList)) {
                return 2;
            }
        }
        return 3;
    }

    @Override
    public HrUserVO getCurrentUserInfo(TokenUser tokenUser) {
        UserDO userDO = userProviderService.selectUserById(tokenUser.getUserId());
        if (Objects.isNull(userDO)) {
            return null;
        }
        HrUserVO hrUser = userDO.to(HrUserVO.class);
        org.jsola.permission.query.RoleMemberQuery roleMemberQuery = new org.jsola.permission.query.RoleMemberQuery();
        roleMemberQuery.setSubjectType(COMPANY_SUBJECT_TYPE);
        roleMemberQuery.setMemberId(hrUser.getId());

        // 获取符合条件的角色成员
        List<RoleMemberListVO> roleMemberList = selectRoleMemberList(roleMemberQuery, tokenUser.getSiteId());
        if (!CollectionUtils.isEmpty(roleMemberList)) {
            RoleMemberListVO roleMember = roleMemberList.get(0);
            hrUser.setRoleId(roleMember.getRoleId());
            hrUser.setRoleName(roleMember.getRoleName());
            hrUser.setChildCompanyId(roleMember.getSubjectId());
            String childCompanyName = userProviderService.getChildCompanyName(roleMember.getSubjectId(), tokenUser.getSiteId());
            hrUser.setChildCompanyName(childCompanyName);
        }
        return hrUser;
    }

    @Override
    public List<String> listChildCompanyId(TokenUser tokenUser) {
        return roleMemberService.findUserHasRightSubjectId(tokenUser.getUserId(), COMPANY_SUBJECT_TYPE, tokenUser.getSiteId());
    }

    @Override
    public HrUserVO smallProgramGetCurrentUserInfo(TokenUser tokenUser) {
        UserDO userDO = userProviderService.selectUserById(tokenUser.getUserId());
        if (Objects.isNull(userDO)) {
            return null;
        }
        HrUserVO hrUser = userDO.to(HrUserVO.class);
        //查询员工信息
        EmpInfoDO empInfoDO = empInfoService.selectEmpByUserId(tokenUser);
        // 有可能登陆的是超管,超管无员工信息
        if (ObjectUtils.isEmpty(empInfoDO)) {
            hrUser.setCompanyName("");
            hrUser.setVerified(false);
        } else {
            //查询公司信息
            CompanyDO companyDO = companyService.selectDOByIdNotSite(empInfoDO.getCompanyId());
            if (ObjectUtils.isEmpty(companyDO)) {
                hrUser.setCompanyName("");
            }
            //员工是否实名认证
            hrUser.setVerified(empInfoDO.getVerified());
            hrUser.setCompanyName(companyDO.getName());
            hrUser.setStatus(empInfoDO.getStatus());
            hrUser.setAvatar(empInfoDO.getEmpPhoto());
        }

        hrUser.setPercentage("20");
        return hrUser;
    }

    @Override
    public List<String> selectHadRoleUserIdBySiteId(TokenUser tokenUser) {
        return roleMemberService.selectHadRoleUserIdBySiteId(tokenUser);
    }


    @Override
    public List<RoleMemberDO> selectAllRoleMemberByUserId(String userId) {
        return roleMemberService.findUserAllRoleMemberList(userId);
    }

    @Override
    public List<RoleMemberDO> selectHrRoleMemberByUserId(String userId) {
        Example example = new Example(RoleMemberDO.class);
        example.and()
                .andIn("subjectType", Arrays.asList("hr", "system"))
                .andEqualTo("memberId", userId);
        List<RoleMemberDO> roleMemberDOList = roleMemberDAO.selectByExample(example);
        if (CollectionUtils.isEmpty(roleMemberDOList)) {
            return new ArrayList<>();
        }
        // 角色信息
        List<Long> roleIds = roleMemberDOList.parallelStream()
                .map(RoleMemberDO::getRoleId).distinct().collect(Collectors.toList());
        Example roleExample = new Example(RoleDO.class);
        roleExample.and()
                .andEqualTo("valid", true)
                .andIn("id", roleIds);
        List<RoleDO> roleDOList = roleDAO.selectByExample(roleExample);
        // 角色id-name
        Map<Long, String> roleIdNameMap = roleDOList.parallelStream().collect(Collectors.toMap(BaseDO::getId, RoleDO::getName));
        roleMemberDOList = roleMemberDOList.parallelStream().map(roleMemberDO -> {
            // 角色名称
            String roleName = roleIdNameMap.get(roleMemberDO.getRoleId());
            // 角色被删除 过滤
            if (roleName == null) {
                return null;
            }
            roleMemberDO.setRoleName(roleName);
            return roleMemberDO;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        return roleMemberDOList;
    }

    @Override
    public List<RoleMemberDO> selectHrRoleMemberByUserIdAndSiteId(String userId, String siteId) {
        Example example = new Example(RoleMemberDO.class);
        example.and()
                .andIn("subjectType", Arrays.asList("hr", "system"))
                .andEqualTo("memberId", userId)
                .andEqualTo("siteId", siteId);
        List<RoleMemberDO> roleMemberDOList = roleMemberDAO.selectByExample(example);
        if (CollectionUtils.isEmpty(roleMemberDOList)) {
            return new ArrayList<>();
        }
        List<Long> roleIds = roleMemberDOList.parallelStream()
                .map(RoleMemberDO::getRoleId).distinct().collect(Collectors.toList());
        Example roleExample = new Example(RoleDO.class);
        roleExample.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId)
                .andIn("id", roleIds);
        List<RoleDO> roleDOList = roleDAO.selectByExample(roleExample);
        // 角色id-name
        Map<Long, String> roleIdNameMap = roleDOList.parallelStream().collect(Collectors.toMap(BaseDO::getId, RoleDO::getName));
        roleMemberDOList = roleMemberDOList.parallelStream().map(roleMemberDO -> {
            // 角色名称
            String roleName = roleIdNameMap.get(roleMemberDO.getRoleId());
            // 角色被删除 过滤
            if (roleName == null) {
                return null;
            }
            roleMemberDO.setRoleName(roleName);
            return roleMemberDO;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        return roleMemberDOList;
    }

    @Override
    public List<PermissionDO> getHasRightPermissionListByRightValue(String rightValue) {
        return rightService.getHasRightPermissionListByRightValue(rightValue);
    }

    @Override
    public PermissionDO selectDOById(Long id) {
        return permissionService.selectDOById(id, PermissionConstants.DEFAULT_SITE_ID);
    }

    @Override
    public List<GroupListVO> selectGroupTree(GroupQuery groupQuery, TokenUser tokenUser) {
        return groupService.selectGroupTree(groupQuery, tokenUser);
    }

    @Override
    public GroupDO selectGroupById(String groupId, TokenUser tokenUser) {
        return groupService.selectDOById(groupId, tokenUser.getSiteId());
    }

    @Override
    public List<String> selectGroupByIdByParent(List<String> parentIdList, String siteId) {
        return groupService.selectByParentIdList(parentIdList, siteId);
    }

    @Override
    public List<GroupDO> selectGroupByParentId(String parentId, TokenUser tokenUser) {
        return groupService.selectByParentId(parentId, tokenUser.getSiteId());
    }

    @Override
    public GroupVO saveGroup(GroupAddDTO groupAddDTO, TokenUser tokenUser) {
        return groupService.save(groupAddDTO, tokenUser);
    }

    @Override
    public void bachSaveGroupUser(List<GroupUserDO> bachSaveList, TokenUser tokenUser) {
        groupUserService.bachSave(bachSaveList);
    }

    @Override
    public void updateGroup(GroupUpdateDTO groupUpdateDTO, TokenUser tokenUser) {
        groupService.update(groupUpdateDTO, tokenUser);
    }

    @Override
    public void deleteUserFromGroupId(String groupId) {
        groupUserService.deleteFromGroupId(groupId);
    }

    @Override
    public List<GroupListVO> findGroupsByIds(List<String> groupIdList, String siteId) {
        return groupService.findGroupsByIds(groupIdList, siteId);
    }

    @Override
    public List<GroupUserDO> selectUserByGroupId(String groupId) {
        return groupUserService.selectUserByGroupId(groupId);
    }

    @Override
    public void deleteGroup(String groupId, TokenUser tokenUser) {
        groupService.deleteByIds(tokenUser, groupId);
    }

    @Override
    public List<GroupUserDO> selectGroupCurrentUser(String groupType, TokenUser tokenUser) {
        GroupUserQuery query = new GroupUserQuery();
        query.setGroupType(groupType);
        query.setUserId(tokenUser.getUserId());
        return groupUserService.selectGroupUser(query, tokenUser.getSiteId());
    }

    @Override
    public void filterGroupId(List<String> groupIdList, String siteId) {
        groupService.filterGroupId(groupIdList, siteId);
    }

    @Override
    public List<BuildParentGroupListVO> buildParentGroupList(List<String> groupIdList, String groupType, TokenUser tokenUser) {
        return groupService.buildParentGroupList(groupIdList, groupType, tokenUser);
    }

    @Override
    public List<String> selectSiteGroupUser(String groupType, String siteId) {
        List<GroupListVO> siteGroup = groupService.selectSiteGroup(groupType, siteId);
        List<GroupUserDO> groupUserList = groupUserService.selectUserByGroupId(siteGroup.get(0).getId());
        if(CollectionUtils.isEmpty(groupUserList)){
            return new ArrayList<>();
        }
        return groupUserList.stream().map(GroupUserDO::getUserId).collect(Collectors.toList());
    }

    @Override
    public GroupListVO selectSiteGroup(String groupType, String siteId) {
        List<GroupListVO> siteGroup = groupService.selectSiteGroup(groupType, siteId);
        return siteGroup.get(0);
    }

    public boolean isHrAdmin(String phone, TokenUser tokenUser){
        List<RoleMemberDO> list = roleMemberService.findUserAllRoleMemberListByPhone(phone);
        if (!CollectionUtils.isEmpty(list)) {
            return true;
        }
        return false;
    }

}
